from flask import Flask, request, jsonify
from tasks import process_static_page, process_Ajax_content, process_translation
from celery.app.control import Control  # 修改导入路径
from db import create_task

app = Flask(__name__)
celery_control = Control(process_static_page.app)  # 初始化 Control 对象

@app.route('/add_static_task', methods=['POST'])
def add_static_task():
    data = request.get_json()
    domain = data.get('domain')
    page_url = data.get('page_url')
    task_id = data.get('task_id')

    if not all([domain, page_url, task_id]):
        return jsonify({"error": "Missing required fields"}), 400
    
    # URL 校验
    import re
    if not re.match(r'^https?://[^\s/$.?#].[^\s]*$', page_url):
        return jsonify({"error": "Invalid page_url"}), 400

    create_task(domain, page_url, task_id)
    task = process_static_page.delay(domain, page_url, task_id)
    return jsonify({"task_id": task.id, "status": "Task submitted"}), 200

@app.route('/add_Ajax_task', methods=['POST'])
def add_Ajax_task():
    data = request.get_json()
    domain = data.get('domain')
    page_url = data.get('page_url')
    task_id = data.get('task_id')

    if not all([domain, page_url, task_id]):
        return jsonify({"error": "Missing required fields"}), 400
    
    create_task(domain, page_url, task_id)
    task = process_Ajax_content.delay(domain, page_url, task_id)
    return jsonify({"task_id": task.id, "status": "Task submitted"}), 200

@app.route('/revoke_task/<task_id>', methods=['DELETE'])
def revoke_task(task_id):
    celery_control.revoke(task_id, terminate=True)  # 使用 Control 对象
    return jsonify({"task_id": task_id, "status": "Task revoked"}), 200

# 新增翻译任务接口
@app.route('/add_translation_task', methods=['POST'])
def add_translation_task():
    data = request.get_json()
    pre_trans_file = data.get('pre_trans_file')  # 初始字典文件路径
    task_id = data.get('task_id')
    target_lang = data.get('target_lang', 'zh-cn')

    if not all([pre_trans_file, task_id]):
        return jsonify({"error": "Missing required fields"}), 400

    create_task("translation", pre_trans_file, task_id)
    task = process_translation.delay(pre_trans_file, task_id, target_lang)
    return jsonify({"task_id": task.id, "status": "Translation task submitted"}), 200

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)